package Server.gui;

import Server.domain.threads.BomberManChatServerThread;
import Server.domain.BomberManChatServer;
import Server.domain.BomberManGameServer;
import Server.domain.threads.BomberManGameServerThread;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author Michael Heughebaert <michael.heughebaert.r2449@student.hogent.be>
 */
public class BomberManServerGUI extends JFrame implements ActionListener, WindowListener {

    //Gui Components
    private JTextField tf_TCPPortNumber;
    private JTextField tf_UDPPortNumber;
    private JButton b_serverStartStop;
    private JTextArea ta_events;
    private JTextArea chat, event;
    
    //Classes
    private BomberManChatServer bmcServer;
    private BomberManGameServer bmgServer;
    private SimpleDateFormat sdf;
    
    //Variables
    private int tcpPortNumber;
    private int udpPortNumber;

    //Constructor with default portNumber from startUp
    public BomberManServerGUI(int tcpPortNumber, int udpPortNumber) {
        //Set frame title
        super("Bomberman Server v0.6b");
        
        //Initialize Server
        bmcServer = null;
        
        //Initialize SimpleDateFormat
        sdf = new SimpleDateFormat("HH:mm:ss");
        
        //Initialize portNumber
        this.tcpPortNumber = tcpPortNumber;
        this.udpPortNumber =udpPortNumber;

        //Initialize GUI
        initGui();
    }

    //Method for initializing the GUI
    private void initGui() {
        //Initialize topPanel
        JPanel topPanel = new JPanel();
       

        //Initialize label and textfield for TCP portNumber handling
        topPanel.add(new JLabel("Chat Port number: "));
        tf_TCPPortNumber = new JTextField(15);
        tf_TCPPortNumber.setText("" + tcpPortNumber);
        topPanel.add(tf_TCPPortNumber);

        
          //Initialize label and textfield for UDP portNumber handling
        topPanel.add(new JLabel("Game Port number: "));
        tf_UDPPortNumber = new JTextField(15);
        tf_UDPPortNumber.setText("" + udpPortNumber);
        topPanel.add(tf_UDPPortNumber);
        
        
        //Initialize button for server start/stop handling
        b_serverStartStop = new JButton("Start Server");
        b_serverStartStop.addActionListener(this);
        topPanel.add(b_serverStartStop);
        
        // the event and chat room
	        JPanel center = new JPanel(new GridLayout(2,1));
	        chat = new JTextArea(80,80);
	        chat.setEditable(false);
	        appendRoom("Chat room.\n");
	        center.add(new JScrollPane(chat));
	        event = new JTextArea(80,80);
	        event.setEditable(false);
	        appendEvent("Events log.\n");
	        center.add(new JScrollPane(event));
	        add(center);
        
        //Add border around topPanel
        topPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

        //Add initialized topPanel to frame
        topPanel.setPreferredSize(new Dimension(400, 100));
        add(topPanel, BorderLayout.NORTH);

        //Initialize centerPanel
        JPanel centerPanel = new JPanel(new GridLayout(1,1));

        //Initialize textArea for server messages handling
        ta_events = new JTextArea();
        ta_events.setEditable(false);
        ta_events.setLineWrap(true);
        centerPanel.add(new JScrollPane(ta_events));

        //Set inital text in eventWindow
        appendEventMessage("Initialize Server.");
        
        //Add padding around centerPanel
        centerPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

        //Add initialized centerPanel to frame
        add(centerPanel);

        //Initialize and show frame
        addWindowListener(this);
        setSize(400, 600);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    //Method for appending messages to the textArea
    public void appendEventMessage(String eventString) {
        //Format eventString
        String eventMessage = sdf.format(new Date()) + "> " + eventString + "\n";
                
        //Append the eventString in the textArea
        ta_events.append(eventMessage);
        
        //Move the caret to the final rule
        ta_events.setCaretPosition(ta_events.getText().length() - 1);
    }

    @Override
    //Method to handle the start/stop button
    public void actionPerformed(ActionEvent e) {
        //Handling stopping the server
        if (bmcServer != null || bmgServer !=null) {
            bmcServer.stop();
            bmcServer = null;
            bmgServer.stop();
            bmgServer = null;
            tf_TCPPortNumber.setEditable(true);
            tf_UDPPortNumber.setEditable(true);
            b_serverStartStop.setText("Start Server");
            return;
        }

        int tcpPort;
        int udpPort;

        //Handling starting the server
        //Parsing the textField for Integer
        try {
            tcpPort = Integer.parseInt(tf_TCPPortNumber.getText().trim());
        } catch (NumberFormatException ex) {
            appendEventMessage("Invalid tcp port number.");
            return;
        }
        
        try {
            udpPort = Integer.parseInt(tf_UDPPortNumber.getText().trim());
        } catch (NumberFormatException ex) {
            appendEventMessage("Invalid udp port number.");
            return;
        }

        //Initialize Chat Server and start thread
        bmcServer = new BomberManChatServer(tcpPort, this);
        new BomberManChatServerThread(bmcServer).start();
        
        // Initialize Game Server and start thread
         bmgServer = new BomberManGameServer(udpPort, this);
         // heb een playerlist nodig
        new BomberManGameServerThread(bmgServer).start();
        //Change components
        b_serverStartStop.setText("Stop Server");
        tf_TCPPortNumber.setEditable(false);
        tf_UDPPortNumber.setEditable(false);
    }

    @Override
    //Method for handling user action: close window
    public void windowClosing(WindowEvent e) {
        //Stop the server
        if (bmcServer != null) {
            try {
                bmcServer.stop();
            }
            catch(Exception ex) {
            }
            bmcServer = null;
        }
        
        //Close the window
        dispose();
        System.exit(0);
        
    }
    
    public void appendRoom(String str) {
	        chat.append(str);
	        chat.setCaretPosition(chat.getText().length() - 1);
	    }
	public void appendEvent(String str) {
	        event.append(str);
	        event.setCaretPosition(chat.getText().length() - 1);
	         
	    }

    
    //Unused overrides
    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }
    
    public JTextField getTf_TCPPortNumber() {
        return tf_TCPPortNumber;
    }

    public JTextField getTf_UDPPortNumber() {
        return tf_UDPPortNumber;
    }
    
    public JButton getB_serverStartStop() {
        return b_serverStartStop;
    }
}